package com.benben.springSecurity.weiwei;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

//对于维护蛇的身体，如果没吃到食物，则加上头去掉尾巴，如果吃到了就不去掉尾巴
class Position {
    int x,y;
    Position(int x, int y){
        this.x = x;
        this.y = y;
    }
    public String toString(){
        return x + "," + y;
    }
}
public class SnakeGame {
    private Set<String> board = new HashSet<>();
    private int[][] food;
    private int eat = 0;
    private LinkedList<Position> snake = new LinkedList<Position>();
    private int width,height;
    private boolean eat(int x,int y){
        if(eat >= food.length){
            return false;
        }
        if(food[eat][0] < 0 || food[eat][0] >=height || food[eat][1] < 0 || food[eat][1] >= width){
            return false;
        }
        if(x == food[eat][0] && y == food[eat][1]){
            return true;
        }
        return false;
    }
    public SnakeGame(int width,int height,int[][] food){
        this.food = food;
        this.width = width;
        this.height = height;
        Position head = new Position(0,0);
        this.snake.add(head);
        board.add(head.toString());
    }
    public int move(String direction){
        Position head = snake.getFirst();
        Position next = new Position(head.x,head.y);
        if("U".equals(direction)){
            next.x--;
        }else if("D".equals(direction)){
            next.x++;
        }else if("L".equals(direction)){
            next.y--;
        }else if("R".equals(direction)){
            next.y++;
        }else{
            return -1;
        }
        if(next.x<0 || next.x>=height || next.y<0 || next.y>=width){
            return -1;
        }
        String nextStr = next.toString();
        if(eat(next.x,next.y)){ //吃到食物了
            snake.addFirst(next);
            board.add(nextStr);
            return ++eat;
        }
        //没吃到食物
        Position tail = snake.getLast();
        board.remove(tail.toString());
        snake.removeLast();
        if(board.contains(nextStr)){//首尾相撞的情况
            return -1;
        }
        snake.addFirst(next);
        board.add(nextStr);
        return eat;
    }
}
